package com.bite.blog.utils;

import com.bite.blog.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;


@Slf4j
public class JwtUtils {
    private static final long JWT_EXPIRATION = 60 * 60 * 1000;  //过期时间
    //生成key
    private static final String secretStr = "asdgfhgkjyhgjkhgkjhggkhgkhjgkhgkhjgk";
    private static final Key key = Keys.hmacShaKeyFor(secretStr.getBytes());

    /*
     * 生成token
     * */
    public static String genJwtToken(Map<String, Object> claim) {
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))  //设置过期时间
                .signWith(key)  //签名算法
                .compact();
        return token;
    }


    /*
     *  校验token
     * Claims 为 null 表示校验失败
     * */
    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();  //创建解析器, 设置签名密钥
        Claims claims = null;
        //抛出异常就证明token错误
        try {
            claims = build.parseClaimsJws(token).getBody();  //解析token
        } catch (Exception e) {
            log.error("解析token失败,token:{}",token);
            return null;
        }
        return claims;
    }

    /*
    * 提取token里的用户ID*/
    public static Integer getIdByToken(String token) {
        Claims claims = parseToken(token);  //解析token
        if (claims != null) {
            Integer userId = (Integer)claims.get(Constants.TOKEN_ID);  //取出token里的id
            if (userId > 0) {
                return userId;
            }
        }
        return null;
    }
}
